<template>
    <div class="page-wrap" v-loading="loading">
        <div class="page-header-wrap">
            <a-page-header @back="handleBack">
                <template #subTitle>
                    <span style="color: #000; font-size: 20px">【{{ detailData.versionNumber }}】【{{ detailData.versionName }}】</span>
                </template>
                <template #tags v-if="detailData.status === '3'">
                    <a-tag color="red" v-if="detailData.onlineStatus === '2'">延期</a-tag>
                    <a-tag color="blue" v-if="detailData.onlineStatus === '1'">正常</a-tag>
                </template>
                <flexbox style="font-size: 14px">
                    <flexbox v-if="isOutsideSystem">
                        <span class="caption-font-color">上线需求：</span>
                        <span class="font-w-b">{{ detailData.onlineProductCount || 0 }}</span>
                    </flexbox>
                    <flexbox v-else>
                        <span class="caption-font-color">上线产品需求：</span>
                        <span class="font-w-b">{{ detailData.onlineProductCount || 0 }}</span>
                    </flexbox>
                    <flexbox style="margin-left: 160px" v-if="!isOutsideSystem">
                        <span class="caption-font-color">解决业务需求：</span>
                        <span class="font-w-b primary-color">{{ detailData.onlineBusinessCount || 0 }}</span>
                    </flexbox>
                    <router-link
                        :to="{
                            path: '/energyManage/versionReportHistory/requestList',
                            query: { id: detailData.onlineBusinesses, versionNumber: detailData.versionNumber },
                        }"
                        class="margin-l-16"
                        v-if="detailData.onlineBusinessCount"
                    >
                        查看明细
                    </router-link>
                </flexbox>
                <a-form style="margin-top: 8px" layout="inline" labelAlign="left" v-if="detailData.id">
                    <a-row>
                        <a-col :span="4">
                            <a-form-item label="所属产品" :span="24">
                                <a-tooltip :title="detailData.systemName">
                                    <span class="font-w-b" v-fitText style="width: 100%">{{ detailData.systemName }}</span>
                                </a-tooltip>
                            </a-form-item>
                        </a-col>
                        <a-col :span="5">
                            <a-form-item label="迭代周期" :span="24">
                                <span class="font-w-b"
                                    >{{
                                        detailData?.pmpRequireTrackTimeDTO.versionRanddPlanStartTime
                                            ? $moment(detailData?.pmpRequireTrackTimeDTO.versionRanddPlanStartTime).format('YYYY-MM-DD')
                                            : '暂无'
                                    }}~{{
                                        detailData?.pmpRequireTrackTimeDTO.versionExpectTime
                                            ? $moment(detailData?.pmpRequireTrackTimeDTO.versionExpectTime).format('YYYY-MM-DD')
                                            : '暂无'
                                    }}</span
                                >
                            </a-form-item>
                        </a-col>
                        <a-col :span="3">
                            <a-form-item label="状态" :span="24">
                                <flexbox class="success-color"> <span style="font-size: 50px; margin-top: -8px">·</span><span>已上线</span> </flexbox>
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-form-item label="实际上线日期" :span="24">
                                <span class="font-w-b">{{
                                    detailData.pmpRequireTrackTimeDTO.versionOnlineRealTime
                                        ? $moment(detailData.pmpRequireTrackTimeDTO.versionOnlineRealTime).format('YYYY-MM-DD')
                                        : ''
                                }}</span>
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-form-item
                                a-form-item
                                :label="detailData.pmpRequireTrackTimeDTO.onlineTimeOffset >= 0 ? '流程延期天数' : '流程提前天数'"
                                :span="24"
                            >
                                <span class="font-w-b">{{
                                    detailData.pmpRequireTrackTimeDTO.onlineTimeOffset >= 0
                                        ? detailData.pmpRequireTrackTimeDTO.onlineTimeOffset
                                        : ` ${Math.abs(detailData.pmpRequireTrackTimeDTO.onlineTimeOffset)}`
                                }}</span>
                                <a @click="jumpTo(detailData.id)" class="margin-l-8">查看详情</a>
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-form-item label="负责人" :span="24">
                                <span class="font-w-b">{{ detailData.createUser }}</span>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </a-page-header>
            <img src="@/assets/images/badge-track.png" style="width: 130px; height: 100%; position: absolute; top: 0px; right: 0" />
            <div
                style="
                    width: 130px;
                    height: 100%;
                    position: absolute;
                    top: 0px;
                    right: 0;
                    display: flex;
                    align-items: center;
                    padding-left: 40px;
                    color: #fff;
                "
            >
                <div>版本能效报告</div>
            </div>
        </div>
        <div class="page-cont" v-if="detailData.id">
            <!-- 自研or外采or外部系统的 -->
            <component ref="comRef" :is="comName" :detail="detailData" v-if="devType" :onlineStatus="form.onlineStatus" />
            <!-- 操作 -->
            <h-section title="延期结果复核" collapse style="padding: 0">
                <a-form ref="ruleFormRef" :model="form" :rules="rules">
                    <a-row>
                        <a-col :span="24">
                            <a-form-item label="预计上线时间" :span="24">
                                <span>
                                    {{
                                        detailData.pmpRequireTrackTimeDTO.versionExpectTime
                                            ? $moment(detailData.pmpRequireTrackTimeDTO.versionExpectTime).format('YYYY-MM-DD')
                                            : ''
                                    }}
                                </span>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="实际上线时间" :span="24" name="modifyOnlineRealTime">
                                <span v-if="defaultStatus === form.onlineStatus">
                                    {{
                                        detailData.pmpRequireTrackTimeDTO.versionOnlineRealTime
                                            ? $moment(detailData.pmpRequireTrackTimeDTO.versionOnlineRealTime).format('YYYY-MM-DD')
                                            : ''
                                    }}
                                </span>
                                <div v-else>
                                    <HDatePickerCell v-model:value="form.modifyOnlineRealTime" :disabledDate="false" />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="延期上线" :span="24">
                                <span v-if="disabled">
                                    {{ form.onlineStatus === '1' ? '正常' : '延期' }}
                                </span>
                                <a-select
                                    placeholder="请选择"
                                    v-model:value="form.onlineStatus"
                                    style="width: 200px"
                                    @change="handleSelectChange"
                                    v-else
                                >
                                    <a-select-option key="1"> 正常 </a-select-option>
                                    <a-select-option key="2"> 延期 </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="延期结果调整原因" :span="24" name="onlineStatusChangeReason">
                                <span v-if="disabled">
                                    {{ $filters.onlineStatusChangeReasonFilter(form.onlineStatusChangeReason) }}
                                </span>
                                <!-- <a-textarea v-model:value="form.onlineStatusChangeReason" :maxlength="255" placeholder="请输入" :rows="2" v-else style="width: 500px" /> -->
                                <a-select v-model:value="form.onlineStatusChangeReason" style="width: 200px" allowClear v-else>
                                    <a-select-option key="1">同一生产变更窗口期</a-select-option>
                                    <a-select-option key="2">遇节假日</a-select-option>
                                    <a-select-option key="3">线上观察</a-select-option>
                                    <a-select-option key="4">等待变更流程审批</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="审批意见" :span="24">
                                <span v-if="disabled">
                                    {{ form.auditOpinion }}
                                </span>
                                <a-textarea v-model:value="form.auditOpinion" placeholder="请输入" :rows="2" v-else style="width: 500px" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </h-section>
            <flexbox justify="flex-end" class="btn-group" v-if="detailData.stage === '2' && !disabled">
                <a-button @click="handleSave">保存</a-button>
                <a-button type="primary" @click="handleNext('')" v-if="detailData.createBy === $store.getters.userInfo.employeeDTO.empId"
                    >提交报告</a-button
                >
            </flexbox>
            <flexbox style="padding: 0 16px" justify="flex-end" class="btn-group" v-if="['3', '4', '5'].includes(detailData.stage)">
                <flexbox v-if="!disabled">
                    <a-button @click="handleNext('否')">不通过</a-button>
                    <a-button type="primary" @click="handleNext('是')">通过</a-button>
                </flexbox>
            </flexbox>

            <history-record :detail="detailData" style="padding: 0" />
        </div>
    </div>
</template>

<script lang="ts">
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { HDatePickerCell } from '@/components';
import waicai from '@/views/energyManage/versionReportHistory/detail/Waicai/index.vue';
import ziyan from '@/views/energyManage/versionReportHistory/detail/Ziyan/index.vue';
import JiraIssue from '@/views/energyManage/versionReportHistory/detail/JiraIssue/index.vue';
import HistoryRecord from '@/views/energyManage/versionReportHistory/detail/HistoryRecord/index.vue';
import api from '@/api';
import store from '@/store';
import { message } from 'ant-design-vue';
import { defineComponent, ref, unref, reactive, toRefs, computed } from 'vue';
export default defineComponent({
    components: {
        waicai,
        ziyan,
        HistoryRecord,
        HDatePickerCell,
        JiraIssue
    },
    setup() {
        const { route, router, handleBack } = useRouterApi({
            backQuery: {
                path: '/energyManage/versionReportHistory'
            }
        });
        const ruleFormRef = ref<any>();
        const state = reactive<any>({
            loading: false,
            detailData: {},
            devType: '',
            form: {
                auditOpinion: '',
                onlineStatus: '',
                onlineStatusChangeReason: '',
                modifyOnlineRealTime: '' // 修改后的实际上线时间
            },
            oldOnlineStatus: null
        });
        const comRef = ref<any>();
        // 默认状态
        const defaultStatus = computed(() => {
            return state.detailData.pmpRequireTrackTimeDTO.onlineTimeOffset >= 0.9 ? '2' : '1';
        });
        // 是否是外部系统
        const isOutsideSystem = computed(() => {
            return state.detailData.id ? state.detailData.pmpProductDetailDTO.isOutsideSystem === '1' : false;
        });
        const comName = computed(() => {
            if (isOutsideSystem.value) {
                return 'JiraIssue';
            } else {
                return state.devType === '1' ? 'waicai' : 'ziyan';
            }
        });
        const disabled = computed(() => {
            if (state.detailData.agentUserEmpId) {
                return !(state.detailData.agentUserEmpId.includes(store.getters.userInfo.employeeDTO.empId) && +state.detailData.stage < 5);
            } else {
                return true;
            }
        });
        const rules = computed(() => {
            let rules: any = {};
            if (unref(defaultStatus) !== state.form.onlineStatus) {
                rules = {
                    onlineStatusChangeReason: [{ required: true, message: '延期结果调整原因不能为空', trigger: 'blur' }],
                    modifyOnlineRealTime: [{ required: true, message: '实际上线时间不能为空', trigger: 'blur' }]
                };
            } else {
                rules = {};
            }
            return unref(disabled) ? {} : rules;
        });
        const handleSelectChange = () => {
            state.form.modifyOnlineRealTime = '';
            unref(ruleFormRef) && unref(ruleFormRef).clearValidate();
        };
        const getDetailData = async () => {
            state.loading = true;
            const query = {
                id: route.query.id
            };
            const { success, moule, errorMsg } = await api.versionStatisticsModel.findById(query);
            if (success) {
                // 阶段是2的，清空流程意见
                moule.auditOpinion = '';
                state.form.auditOpinion = moule.auditOpinion;
                // 1正常 2延期
                if (moule.onlineStatus) {
                    state.form.onlineStatus = moule.onlineStatus;
                } else {
                    state.form.onlineStatus = moule.pmpRequireTrackTimeDTO.onlineTimeOffset >= 0.9 ? '2' : '1';
                }

                state.oldOnlineStatus = moule.onlineStatus;
                state.form.onlineStatusChangeReason = moule.onlineStatusChangeReason;
                state.form.modifyOnlineRealTime = moule.pmpRequireTrackTimeDTO.modifyOnlineRealTime;
                state.devType = moule.devType;
                state.detailData = { ...moule };
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
        };
        const handleSave = async () => {
            const query = {
                ...unref(comRef).detailData,
                pmpRequireTrackTimeDTO: {
                    ...unref(comRef).detailData.pmpRequireTrackTimeDTO,
                    modifyOnlineRealTime: state.form.modifyOnlineRealTime
                },
                ...state.form
            };
            const { success, errorMsg } = await api.versionStatisticsModel.save(query);
            if (success) {
                message.success('保存成功');
                getDetailData();
            } else {
                message.error(errorMsg);
            }
        };
        const handleNext = async (pass = null) => {
            state.loading = true;
            const res = await unref(comRef).validate();
            if (res) {
                unref(ruleFormRef)
                    .validate()
                    .then(
                        async () => {
                            const query = {
                                ...unref(comRef).detailData,
                                pmpRequireTrackTimeDTO: {
                                    ...unref(comRef).detailData.pmpRequireTrackTimeDTO,
                                    modifyOnlineRealTime: state.form.modifyOnlineRealTime
                                },
                                ...state.form,
                                pass
                            };
                            const { success, errorMsg } = await api.versionStatisticsModel.auditProcess(query);
                            if (success) {
                                // handleBack();
                                router.push({
                                    path: '/workbench'
                                });
                            } else {
                                message.error(errorMsg);
                            }
                            state.loading = false;
                        },
                        () => {
                            state.loading = false;
                        }
                    );
            } else {
                state.loading = false;
            }
        };
        const jumpTo = (id) => {
            router.push({
                path: '/energyManage/timeliness',
                query: {
                    id
                }
            });
        };
        getDetailData();
        return {
            comRef,
            ruleFormRef,
            isOutsideSystem,
            disabled,
            comName,
            rules,
            defaultStatus,
            ...toRefs(state),
            handleSave,
            handleNext,
            handleBack,
            jumpTo,
            handleSelectChange
        };
    }
});
</script>

<style scoped lang="less">
.page-wrap {
    position: relative;
    height: 100%;
    .page-header-wrap {
        background: #fff;
        position: sticky;
        top: 0;
        z-index: 9;
        border-bottom: 1px solid #f1f1f1;
        border-top: 1px solid #f1f1f1;
        margin-bottom: 24px;
        &::before {
            content: '';
            position: absolute;
            width: 6px;
            height: 100%;
            background: @primary-color;
            top: 0;
            left: 0;
            z-index: 1;
        }
        .extra-wrap {
            position: absolute;
            right: 40px;
            bottom: 22px;
            color: #000;
            cursor: pointer;
        }
        ::v-deep(.ant-form-item-label) {
            min-width: 0;
        }
    }
    .page-cont {
        margin-top: 24px;
        position: relative;
        background: #fff;
        padding: 24px 16px;
        .btn-group {
            margin-top: 16px;
            button + button {
                margin-left: 8px;
            }
        }
    }
    .page-header {
        padding: 0 16px;
    }
}
// 去掉表头颜色
::v-deep(.ant-table-thead) > tr > th {
    background: #fafafa !important;
    font-weight: 400;
    color: #505a6e;
}
::v-deep(.ant-divider) {
    border-top: 2px solid #eaf5fe;
}
</style>